package com.ybdz.scanner.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.ybdz.scanner.R;
import com.ybdz.scanner.adapter.chuKuDanAdapter;
import com.ybdz.scanner.api.ApiStore;
import com.ybdz.scanner.api.Constant;
import com.ybdz.scanner.base.BaseActivity;
import com.ybdz.scanner.bean.ChuKuDanBean;
import com.ybdz.scanner.bean.TakeInventoryBean;
import com.ybdz.scanner.event.ObjEvent;
import com.ybdz.scanner.receiver.ScannerInterface;
import com.ybdz.scanner.utils.ListUtil;
import com.ybdz.scanner.utils.MyApplication;
import com.ybdz.scanner.utils.MyToast;
import com.ybdz.scanner.utils.UIUtils;
import com.ybdz.scanner.view.FullyLinearLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @ClassName: ChuKuDanActivity
 * @author: zhao
 * @Description: 出库单界面
 * @date 2018/2/24 17:00
 */
public class ChuKuDanActivity extends BaseActivity {

    @BindView(R.id.rv)
    RecyclerView mRv;
    @BindView(R.id.tv_chuku_id)
    TextView mTvId;
    @BindView(R.id.ll_head)
    LinearLayout mLlHead;
    @BindView(R.id.empty)
    QMUIEmptyView mEmpty;
    @BindView(R.id.top_hint)
    LinearLayout mTopHint;

    private TakeItemResultReceiver mResultReceiver;
    private ScannerInterface mScanner;
    private boolean isContinue = false;        //连续扫描的标志
    private chuKuDanAdapter mAdapter;
    private String outFormId;
    private String id;
    private ChuKuDanActivity chuKuDanActivity;
    private String oldResult="";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_look_take);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        mEmpty.show(true);
        initRecycleView();
        chuKuDanActivity = this;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mResultReceiver = new TakeItemResultReceiver();
        mScanner = initScanner(mResultReceiver);
        initData(id);
    }

    @Override
    protected void onPause() {
        super.onPause();
        finishScanner(mResultReceiver);
    }

    private void tryHttp(String msg) {
        mEmpty.show(false, msg, null, "点击重试", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEmpty.show(true);
                initData(id);
            }
        });
    }

    /**
     * 出库单的网络请求
     *
     * @param id
     */
    private void initData(final String id) {
        if (id == null || id.length() <= 0){
            Log.d("ChuKuDanid值:",String.valueOf(id));
            onBackPressed();
            return;
        }
        ApiStore.takeTable(id).enqueue(new Callback<ChuKuDanBean>() {
            @Override
            public void onResponse(Call<ChuKuDanBean> call, Response<ChuKuDanBean> response) {
                if (response.isSuccessful() && response.code() == 200) {
                    ChuKuDanBean body = response.body();
                    if (body != null){
                        if (body.getStatus() == 200){
                            mEmpty.hide();
                            ChuKuDanBean.DataBean data = body.getData();
                            if (data != null){
                                List<ChuKuDanBean.DataBean.OutBatchBean> outBatch = data.getOutBatch();
                                mAdapter = new chuKuDanAdapter(ChuKuDanActivity.this,outBatch);
                                mRv.setAdapter(mAdapter);
                                mTvId.setText(String.valueOf(data.getOutFormCode()));
                                //保存最近的出库单号
                                String outFormCode = ListUtil.getOutFormCode();
                                //出库单不相同，则情况出库记录；
                                if (!ListUtil.getOutFormCode().equals(String.valueOf(data.getOutFormCode()))){
                                    ListUtil.setOutFormCode(String.valueOf(data.getOutFormCode()));
                                    ListUtil.cleanChuKUList();  //清空出库单记录；
                                }
                                mAdapter.notifyDataSetChanged();
                                mLlHead.setVisibility(View.VISIBLE);
                                outFormId = String.valueOf(outBatch.get(0).getOutFormId());

                                EventBus.getDefault().postSticky(new ObjEvent("outFormCode",String.valueOf(data.getOutFormCode())));
                            }
                        }else {
                            mEmpty.show(false,"该出库单已经出库完成",null,null,null);
                        }
                    }


                } else {
                    tryHttp("服务器繁忙");
                }
            }

            @Override
            public void onFailure(Call<ChuKuDanBean> call, Throwable t) {
               // hideLoading();
                Log.d("ChuKuDan:",String.valueOf(t.getMessage()));
                tryHttp("数据异常");
            }
        });
    }

    /**
     * 初始化recycleview
     */
    private void initRecycleView() {
        FullyLinearLayoutManager linearLayoutManager = new FullyLinearLayoutManager(this);
        mRv.setNestedScrollingEnabled(false);
        mRv.setLayoutManager(linearLayoutManager);

    }

    @OnClick({R.id.back, R.id.home, R.id.bt_scan, R.id.bt_history})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:                     //返回
                finish();
                break;
            case R.id.home:                     //返回首页
                startActivity(new Intent(ChuKuDanActivity.this, MainActivity.class));
                finish();
                break;
            case R.id.bt_scan:                  //开启扫描
                MyApplication.setScannerClick(Constant.Take_item);
                mScanner.scan_start();
                break;
            case R.id.bt_history:               //查看历史操作
                startActivity(new Intent(ChuKuDanActivity.this,ChuKuLiShiActivity.class));
                break;
        }
    }

    /**
     * 接收EventBus传递的数据
     *
     * @param onResponeEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void getOutFormId(ObjEvent onResponeEvent) {
        if (onResponeEvent.getId().equals("formId")) {
            id = (String) onResponeEvent.getObj();
        }
    }


    /**
     * 指定139的物理按键（中间黄色按键）按下来出发扫描
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 139 && event.getRepeatCount() == 0) {
            mScanner.scan_start();
            MyApplication.setScannerClick("TAKE_ITEM");
        }
        return super.onKeyDown(keyCode, event);
    }

    public boolean onKeyUp(int keyCode, KeyEvent event) {   //按键弹起，停止扫描
        if (keyCode == 139) {
            mScanner.scan_stop();
        } else if (keyCode == 140) {
            mScanner.scan_stop();

            isContinue = !isContinue;
            if (isContinue) {
                mScanner.continceScan(true);
            } else {
                mScanner.continceScan(false);
            }
        }
        return super.onKeyUp(keyCode, event);
    }


    /**
     * 利用广播接收扫描结果
     */
    private class TakeItemResultReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String scanResult = intent.getStringExtra("value");
            //如果条码长度大于0，解码成功。如果解码长度等于0，解码失败。
            Log.d("chukudan1:",String.valueOf(scanResult));
            String action = intent.getAction();
            if (action == null){
                return;
            }
            if (action.equals(Constant.RES_ACTION)) {
                //获取扫描结果
                if (scanResult.length() > 0 && MyApplication.getScannerClick().equals(Constant.Take_item)) {
                    //解码成功
                    if (scanResult.contains(Constant.Ininventoryitem)) {
                        String[] split = scanResult.split(Constant.Sprit);
                        if (split[split.length - 2].equals(Constant.Ininventoryitem)) {

                            String result = split[split.length - 1];
                            getOut(result);

                        } else {
                            MyToast.show(ChuKuDanActivity.this, "未查询到产品信息，请重新扫码。");
                        }
                    } else {
                        MyToast.show(ChuKuDanActivity.this, "未查询到产品信息，请重新扫码。");
                    }

                } else {
                    //扫码失败
                }
            }
        }
    }

    /**
     * 扫描单品的网络请求
     *
     * @param result
     */
    private void getOut(String result) {
        Log.d("chukudan2:",String.valueOf(result));
        showLoading(ChuKuDanActivity.this);
        ApiStore.getTake(result, outFormId).enqueue(new Callback<TakeInventoryBean>() {
            @Override
            public void onResponse(Call<TakeInventoryBean> call, Response<TakeInventoryBean> response) {
                if (response.isSuccessful()) {
                    hideLoading();
                    TakeInventoryBean body = response.body();
                    if(body != null){
                        TakeInventoryBean.DataBean data = body.getData();
                        if (data != null) {
                            int status = data.getStatus();

                            switch (status) {
                                case 100:   //正常状态
                                    EventBus.getDefault().postSticky(data);
                                    startActivity(new Intent(ChuKuDanActivity.this, ChuKuSimpleActivity.class));

                                    //避免短时间重复网络请求
                                    finishScanner(mResultReceiver);
                                    break;
                                case 101:   //产品已出库完成,不能出库
                                    onFail(ChuKuDanActivity.this,"出库已完成,不能出库");
                                    //避免短时间重复网络请求
                                    finishScanner(mResultReceiver);
                                    break;
                                case 102:   //该产品不是应出批次
                                    EventBus.getDefault().postSticky(data);
                                    startActivity(new Intent(ChuKuDanActivity.this, NotChuKuSimpleActivity.class));

                                    //避免短时间重复网络请求
                                    finishScanner(mResultReceiver);
                                    break;
                                case 103:   //该产品已出库
                                    EventBus.getDefault().postSticky(data);
                                    startActivity(new Intent(ChuKuDanActivity.this, ChuKuErrorActivity.class));

                                    //避免短时间重复网络请求
                                    finishScanner(mResultReceiver);
                                    break;
                                default:
                                    MyToast.show(ChuKuDanActivity.this, String.valueOf(body.getMsg()));
                                    //避免短时间重复网络请求
                                    finishScanner(mResultReceiver);
                                    break;

                            }
                        } else {
                            hideLoading();
                            onFail(ChuKuDanActivity.this,"服务器数据异常！");
                            //避免短时间重复网络请求
                            finishScanner(mResultReceiver);
                        }
                    }


                } else {
                    hideLoading();
                    MyToast.show(ChuKuDanActivity.this, "扫码失败");
                    //避免短时间重复网络请求
                    finishScanner(mResultReceiver);
                }
            }

            @Override
            public void onFailure(Call<TakeInventoryBean> call, Throwable t) {
                hideLoading();
                onFailTimeOut(ChuKuDanActivity.this);
                //避免短时间重复网络请求
                finishScanner(mResultReceiver);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }
}
